<?php

namespace StarCloud\Library;

class Exception extends \Exception
{
    protected $errorCodes = [
        // 系统错误
        '10000' => '404',
        '10001' => 'System error',
        '10002' => 'Param error, see doc for more info : %s',
        '10004' => 'Authorization error',
        '10005' => 'Save or update data error: %s',
        '10006' => 'Delete data error: %s',
        '10007' => 'Unsupport mediatype (%s)',
        '10008' => 'System Maintenance',
        '10009' => 'Mac is error',
        '10010' => 'Client time error',
        '10011' => 'User has been banned',
        '10012' => 'The text is illegal',
        '10013' => 'User has been banned temporarily',
        '10014' => 'Operation Rejected',
        '10015' => 'The version is too low, please use after upgrading',
        '10016' => 'Multi Table Field Key Not Exist',
        '10017' => 'Queue Alias Name Is Unknown',
        '10018' => 'Im Channel Config Is Unknown',
        '10019' => '超过最大导出条目限制',
        '10020' => '游客暂未登陆',
        '10021' => '游客没有权限使用功能',
    ];

    public function __construct()
    {
        $args = func_get_args();
        if (count($args) == 0) {
            throw new parent('System error', 10001);
        }

        $errorCode = $args[0];

        if (property_exists($this, 'appErrorCodes') && is_array($this->appErrorCodes)) {
            // 不能用array_merge 会reindex；相同的key，会使用第一个
            $errorCodes = $this->errorCodes + $this->appErrorCodes;
        } else {
            $errorCodes = $this->errorCodes;
        }

        if (!isset($errorCodes[$errorCode])) {
            throw new parent('System error', 10001);
        }
        if (($msgCount = substr_count($errorCodes[$errorCode], '%s')) != count($args) - 1) {
            throw new parent('System error', 10001);
        }
        parent::__construct(vsprintf($errorCodes[$errorCode], array_slice($args, 1, $msgCount)), $errorCode);
    }
}
